package com.attendance.controller;

import com.attendance.pojo.Notice;
import com.attendance.result.LayuiMiniPage;
import com.attendance.service.NoticeServiceImpl;
import com.attendance.web.Result;
import com.attendance.web.ResultCode;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;

/**
 * 公告控制器
 *
 * @author 今朝
 * @date 2021/03/20
 */
@Controller
@RequestMapping("/system/notice")
@RolesAllowed("ADMIN")
public class NoticeController {

    @Autowired
    NoticeServiceImpl noticeService;

    @GetMapping()
    public String table() {
        return "/system/notice/table";
    }

    @GetMapping("/edit")
    public String edit() {
        return "/system/notice/edit";
    }

    @GetMapping("/add")
    public String add() {
        return "/system/notice/add";
    }

    @GetMapping("/edit/{id}")
    public ModelAndView editForId(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("/system/notice/edit");
        Notice notice = noticeService.selectById(id);
        modelAndView.addObject("notice", notice);
        return modelAndView;
    }

    @ResponseBody
    @GetMapping("/listPage")
    public LayuiMiniPage<Notice> getListPage(Integer page, Integer limit, String searchParams) {
        if (searchParams != null) {
            Page<Notice> listPage = noticeService.getListPage(page, limit, searchParams);
            return new LayuiMiniPage<>(200, "查询成功", listPage.getTotal(), listPage.getRecords());
        }
        Page<Notice> listPage = noticeService.getListPage(page, limit);
        return new LayuiMiniPage<>(200, "查询成功", listPage.getTotal(), listPage.getRecords());
    }

    @ResponseBody
    @PostMapping("/update")
    public Result update(Notice notice) {
        if (noticeService.updateById(notice)) {
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }

    @ResponseBody
    @PutMapping("/add")
    public Result add(Notice notice) {
        try {
            if (noticeService.add(notice)) {
                return new Result(ResultCode.SUCCESS);
            } else {
                return new Result(ResultCode.FAIL);
            }
        } catch (Exception e) {
            return new Result(502, e.getMessage(), false);
        }
    }

    @DeleteMapping("delete")
    @ResponseBody
    public Result delete(@RequestParam("ids[]") ArrayList<Integer> ids) {
        if (noticeService.delete(ids)) {
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }

}
